'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useToast } from '@/hooks/use-toast'
import { Save, X, Loader2 } from 'lucide-react'

interface DeviceDetailPageProps {
  deviceId: number
  deviceName: string
  specialtyName: string
  specialtyRoute: string
  defaultTab?: string
}

interface ParameterField {
  id?: number
  table_name: string
  table_code: string
  table_description: string
  field_sequence: number
  field_name: string
  field_column: string
  example_description: string
  data_type: string
  measurement_class: string
  data_source: string
  is_required: boolean
  created_at?: string
  updated_at?: string
}

interface DeviceData {
  device: any
  mapping: any
  parameters: Record<string, any>
  fields: ParameterField[]
  tableMetadata?: {
    table_name: string
    table_code: string
    table_description: string
    field_count: number
  }
}

type ParamType = 'naming' | 'position' | 'base_params'

export default function NewDeviceDetailPage({
  deviceId,
  deviceName,
  specialtyName,
  specialtyRoute,
  defaultTab = "naming"
}: DeviceDetailPageProps) {
  const { toast } = useToast()
  const [tab, setTab] = useState(defaultTab)
  const [deviceData, setDeviceData] = useState<any>(null)
  const [parameterData, setParameterData] = useState<Record<ParamType, DeviceData | null>>({
    naming: null,
    position: null,
    base_params: null
  })
  const [loading, setLoading] = useState(false)
  const [changed, setChanged] = useState<Record<ParamType, boolean>>({
    naming: false,
    position: false,
    base_params: false
  })
  const [editData, setEditData] = useState<Record<ParamType, Record<string, any>>>({
    naming: {},
    position: {},
    base_params: {}
  })

  // 加载设备的完整信息
  const fetchDeviceData = async () => {
    try {
      const res = await fetch(`/api/device-parameters?deviceId=${deviceId}`)
      const data = await res.json()
      
      if (data.success) {
        setDeviceData(data.data)
      } else {
        toast({ 
          title: "加载失败", 
          description: data.error || "加载设备信息失败",
          variant: "destructive"
        })
      }
    } catch (error) {
      toast({ 
        title: "加载失败", 
        description: "网络错误",
        variant: "destructive"
      })
    }
  }

  // 加载特定类型的参数
  const fetchParameters = async (type: ParamType) => {
    setLoading(true)
    try {
      const res = await fetch(`/api/device-parameters?deviceId=${deviceId}&type=${type}`)
      const data = await res.json()
      
      if (data.success) {
        setParameterData(prev => ({ ...prev, [type]: data.data }))
        
        // 初始化编辑数据
        const editObj: Record<string, any> = {}
        if (data.data.parameters) {
          Object.keys(data.data.parameters).forEach(key => {
            if (key !== 'id' && key !== 'created_at' && key !== 'updated_at') {
              editObj[key] = data.data.parameters[key] || ''
            }
          })
        }
        // 如果没有参数数据，根据字段元数据初始化空值
        if (data.data.fields && Object.keys(editObj).length === 0) {
          data.data.fields.forEach((field: ParameterField) => {
            editObj[field.field_name] = ''
          })
        }
        setEditData(prev => ({ ...prev, [type]: editObj }))
        setChanged(prev => ({ ...prev, [type]: false }))
      } else {
        toast({ 
          title: "加载失败", 
          description: data.error || `加载${getTabLabel(type)}失败`,
          variant: "destructive"
        })
      }
    } catch (error) {
      toast({ 
        title: "加载失败", 
        description: "网络错误",
        variant: "destructive"
      })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchDeviceData()
  }, [deviceId])

  useEffect(() => {
    if (deviceData) {
      fetchParameters('naming')
      fetchParameters('position')
      fetchParameters('base_params')
    }
  }, [deviceData])

  // 处理输入变化
  const handleInput = (type: ParamType, fieldName: string, value: any) => {
    setEditData(prev => ({ 
      ...prev, 
      [type]: { ...prev[type], [fieldName]: value } 
    }))
    setChanged(prev => ({ ...prev, [type]: true }))
  }

  // 保存参数
  const handleSave = async (type: ParamType) => {
    setLoading(true)
    try {
      const res = await fetch('/api/device-parameters', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          deviceId,
          type,
          data: editData[type]
        })
      })
      
      const result = await res.json()
      
      if (result.success) {
        toast({ 
          title: "保存成功", 
          description: `${getTabLabel(type)}已保存`
        })
        
        // 重新加载数据
        await fetchParameters(type)
      } else {
        toast({ 
          title: "保存失败", 
          description: result.error || "保存失败",
          variant: "destructive"
        })
      }
    } catch (error) {
      toast({ 
        title: "保存失败", 
        description: "网络错误",
        variant: "destructive"
      })
    } finally {
      setLoading(false)
    }
  }

  // 获取标签页标题
  const getTabLabel = (type: ParamType): string => {
    switch (type) {
      case 'naming': return '对象命名表'
      case 'position': return '位置信息表'
      case 'base_params': return '基础参数表'
      default: return ''
    }
  }

  // 渲染参数表格
  const renderParameterTable = (type: ParamType) => {
    const data = parameterData[type]
    
    if (!data || !data.fields) {
      return (
        <div className="text-center py-8 text-gray-500">
          {loading ? (
            <div className="flex items-center justify-center">
              <Loader2 className="h-6 w-6 animate-spin mr-2" />
              加载中...
            </div>
          ) : (
            '暂无参数定义'
          )}
        </div>
      )
    }

    return (
      <Card>
        <CardHeader>
          <CardTitle>{getTabLabel(type)}</CardTitle>
          {data.mapping && (
            <div className="space-y-1">
              <p className="text-sm text-gray-600">
                设备类型: {data.mapping.classification_name} |
                表名: {data.mapping[`${type}_table`]}
              </p>
              {data.tableMetadata && (
                <p className="text-xs text-gray-500">
                  表代码: {data.tableMetadata.table_code} |
                  字段数: {data.tableMetadata.field_count} |
                  描述: {data.tableMetadata.table_description}
                </p>
              )}
            </div>
          )}
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {data.fields.map((field, index) => (
              <div key={index} className="grid grid-cols-4 items-start gap-4 p-3 border rounded-lg">
                <div className="text-right">
                  <Label htmlFor={`${type}-${field.field_name}`} className="font-medium">
                    {Array.isArray(field.field_name) ? field.field_name[0] : field.field_name}
                  </Label>
                  <div className="text-xs text-gray-500 mt-1">
                    序号: {field.field_sequence}
                  </div>
                </div>
                <div className="col-span-2">
                  <Input
                    id={`${type}-${field.field_name}`}
                    type={field.data_type === '数值型' ? 'number' : 'text'}
                    value={editData[type][field.field_name] || ''}
                    onChange={(e) => handleInput(type, field.field_name, e.target.value)}
                    placeholder={field.example_description || `请输入${Array.isArray(field.field_name) ? field.field_name[0] : field.field_name}`}
                    required={field.is_required}
                  />
                  {field.example_description && (
                    <div className="text-xs text-gray-500 mt-1">
                      示例: {field.example_description}
                    </div>
                  )}
                </div>
                <div className="text-sm text-gray-500 space-y-1">
                  <div>类型: {field.data_type}</div>
                  {field.measurement_class && field.measurement_class !== '—' && (
                    <div>计量类: {field.measurement_class}</div>
                  )}
                  {field.data_source && (
                    <div>来源: {field.data_source}</div>
                  )}
                </div>
              </div>
            ))}
          </div>
          
          {changed[type] && (
            <div className="flex justify-end gap-2 mt-6">
              <Button 
                variant="outline" 
                onClick={() => fetchParameters(type)} 
                disabled={loading}
              >
                <X className="h-4 w-4 mr-2" />
                取消
              </Button>
              <Button 
                onClick={() => handleSave(type)} 
                disabled={loading}
              >
                <Save className="h-4 w-4 mr-2" />
                {loading ? "保存中..." : "保存"}
              </Button>
            </div>
          )}
        </CardContent>
      </Card>
    )
  }

  if (!deviceData) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin mr-2" />
        加载设备信息中...
      </div>
    )
  }

  return (
    <div className="container mx-auto p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold">{deviceName}</h1>
        <p className="text-gray-600">
          {specialtyName} | 设备ID: {deviceId}
        </p>
        {deviceData.device && (
          <p className="text-sm text-gray-500">
            分类: {deviceData.device.classification_name} ({deviceData.device.classification_code})
          </p>
        )}
      </div>

      <Tabs value={tab} onValueChange={setTab}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="naming">对象命名表</TabsTrigger>
          <TabsTrigger value="position">位置信息表</TabsTrigger>
          <TabsTrigger value="base_params">基础参数表</TabsTrigger>
        </TabsList>
        
        <TabsContent value="naming" className="mt-6">
          {renderParameterTable('naming')}
        </TabsContent>
        
        <TabsContent value="position" className="mt-6">
          {renderParameterTable('position')}
        </TabsContent>
        
        <TabsContent value="base_params" className="mt-6">
          {renderParameterTable('base_params')}
        </TabsContent>
      </Tabs>
    </div>
  )
}
